<template>
	<el-dialog
		width="500px"
		:title="form.id ? '编辑资源' : '添加资源'"
		:visible.sync="dialogVisible"
		:before-close="dialogClose"
	>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item prop="name" label="资源名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item prop="url" label="资源路径">
        <el-input v-model="form.url"></el-input>
      </el-form-item>
      <el-form-item prop="categoryId" label="资源分类">
        <el-select v-model="form.categoryId" style="width:100%">
          <el-option
            v-for="item in resourceCategories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" :rows="5">
        </el-input>
      </el-form-item>
    </el-form>
		
		<span slot="footer" class="dialog-footer">
			<el-button @click="dialogClose">取 消</el-button>
			<el-button type="primary" @click="dialogSubmit">确 定</el-button>
		</span>
	</el-dialog>
</template>

<script lang="ts">
import Vue from 'vue'
import { getResourceCategories } from '@/services/recourse-category'
import { Form } from 'element-ui'

export default Vue.extend({
  name: 'ResourceCreateOrEdit',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    resource: {
      type: Object
    }
  },
  watch: {
    dialogVisible: function () {
      if (this.dialogVisible) {
        this.form = Object.assign(this.form, this.resource)
      }
    }
  },
  data () {
    return {
      resourceCategories: [] as { [key: string]: string | number }[],
      form: {
        name: '',
        url: '',
        categoryId: -1,
        description: ''
      }
    }
  },
  created () {
    this.loadResourceCategorys()
  },
  methods: {
    async loadResourceCategorys () {
      this.form = Object.assign(this.form, this.resource)
      const { data } = await getResourceCategories()
      if (data.code === '000000') {
        this.form.categoryId = data.data[0].id
        this.resourceCategories = data.data
      }
    },
    dialogClose () {
      (this.$refs.form as Form).resetFields()
      this.$emit('close')
    },
    dialogSubmit () {
      this.$emit('submit', this.form)
    }
  }
})
</script>

<style lang="scss"></style>
